package com.qq.BFMRSE.Module;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.fileupload.FileItem;


import com.qq.BFMRSE.Hdfs.hdfsOper;
import com.qq.BFMRSE.util.BFConstants;
import com.qq.BFMRSE.util.objectSerializeUtil;

public class upLoadTool {
	private String  userName;
	private int fileType;
	private String tmpDir;
	public String getTmpDir() {
		return tmpDir;
	}
	public void setTmpDir(String tmpDir) {
		this.tmpDir = tmpDir;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getFileType() {
		return fileType;
	}
	public void setFileType(int fileType) {
		this.fileType = fileType;
	}
	public upLoadTool(String userName,int fileType,String tmpDir){
		this.userName=userName;
		this.fileType=fileType;
		this.tmpDir=tmpDir;
	}
	public upLoadTool(){}
	public void upLoadToHdfs(Object object){
		if(fileType==BFConstants.UPENCRYPTTREE){
			upLoadIndexTree(object);
		}else if(fileType==BFConstants.UPENCRYPTINDEX){
			upLoadEncryIndex((InputStream)object);
		}else if(fileType==BFConstants.UPENCRYPTFILE){
			upLoadEncryFile((List<FileItem>) object);
		}
	}
	public void upLoadIndexTree(Object object){
		System.out.println("test:开始上传索引树！");
		String tmpFileName=tmpDir+File.separator+System.currentTimeMillis()+BFConstants.SERTREENAME;
		System.out.println(tmpFileName);
		try {
			objectSerializeUtil.serialize(object, tmpFileName);
			String des=userName+File.separator+BFConstants.SERTREENAME;
			hdfsOper.upFileToHdfs(tmpFileName, des);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			File tmpFile=new File(tmpFileName);
			if(tmpFile.exists()){
				tmpFile.delete();
			}
		}
	}
	public void upLoadEncryIndex(InputStream is){
		System.out.println("test:开始上传加密索引！");
		String des=userName+File.separator+BFConstants.SERINDEXNAME;
		hdfsOper.upFileToHdfs(is, des);
		
	}
	public void upLoadEncryFile(List<FileItem> items){
		System.out.println("test:开始上传加密文件！");
		for(int i=1;i<items.size();i++){
			FileItem item=items.get(i);
			if(!item.isFormField()){
				String fileName=item.getName();
				InputStream is=null;
				try {
					is=item.getInputStream();
					String des=userName+File.separator+BFConstants.ENCRYDIRNAME+File.separator+fileName;
					hdfsOper.upFileToHdfs(is, des);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	

}
